<template>
    <div class="main flex flex-col">
        <div class="form-header justify-between flex-shrink-0">
            <div>
                <svg @click="routerBack" class="iconpark-icon"><use href="#arrow-left"></use></svg>
                {{ breadcrumbName }}
            </div>
            <div class="flex items-center">
                <el-button @click="submit" :disabled="topicList.length === 0" type="primary">保存</el-button>
                <el-button @click="cancel">取消</el-button>
            </div>
        </div>
        <div class="flex-1 flex container overflow-y-hidden">
            <Thumb
            ref="thumbRef"
            :detail="global.detail"
            @add="onAddTopic" 
            @set-category-id="onSetProgramId" 
            @move="global.onMove = true"
            @end="global.onMove = false"
            />
            <div class="flex-1 p-4 topic-list overflow-y-auto relative">
                <div class="list h-full" ref="topicListDom">
                    <TopicItem
                    v-for="(t, index) in topicList"
                    :item="t"
                    :index="index"
                    :ref="(el: TopicItemType) => addTopicItemRefs(el, t.uid)"
                    :detail="global.detail"
                    :categoryList="categoryList"
                    @del="onDel(t)"
                    @addOpt="onAddOpt(t)"
                    @addAnswer="onAddAnswer(t)"
                    @onFocus="onFocus"
                    @change="(item: any) => topicList[index] = item"
                    @answerFocus="(i: number) => onAnswerFocus(index, i)"
                    class="item"
                    />
                </div>
                <TopicEmpty v-show="topicList.length === 0 && global.onMove === false" class="absolute empty" />
            </div>
        </div>

        <TopicWindow
        ref="topicWindowRef"
        @change="onChangeHtml"
        @close="onCloseContentWindow"
        />
    </div>
</template>

<script setup lang="ts">
import request from '@/Utils/request';
import { createUuid, getInlineStrHtml, routerBack } from '@/Utils/utils';
import { computed, onMounted, reactive, ref, type VNodeRef } from 'vue';
import { useRoute } from 'vue-router';
import Thumb from './Children/Thumb.vue';
import TopicItem from './Children/TopicItem.vue';
import TopicEmpty from './Children/TopicEmpty.vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import type { AnyObj, TopicSaveApi, TopicTypeNumber } from '@/Utils/type';
import TopicWindow from './Children/TopicWindow.vue';
import router from '@/Router';

const route = useRoute();

type TopicItemType = InstanceType<typeof TopicItem>;

const topicWindowRef = ref<InstanceType<typeof TopicWindow>>();

interface TopicSave extends TopicSaveApi {
    uid: string;
}

const global = reactive({
    programId: 0,
    detail: <AnyObj>{},
    onMove: false,
    focusItem: <AnyObj>{},
    focusItemKey: '',
    topicListNew: <TopicSave[]>[],
    topicListIndex: 9999,
    answerIndex: 9999
});

const categoryList = ref<any[]>([]);

const topicItemRefs = reactive<{[prop: string]: TopicItemType}>({});
const thumbRef = ref<InstanceType<typeof Thumb>>();

const topicListDom = ref<HTMLDivElement>();

const topicList = ref<TopicSave[]>([]);

const breadcrumbName = computed(() => {
    let breadcrumbName = route.meta.breadcrumbName;
    if (typeof breadcrumbName === 'function') {
        breadcrumbName = breadcrumbName({
            params: route.params,
        });
    }
    return breadcrumbName;
});

// 新增试题项ref列表
const addTopicItemRefs = (el: TopicItemType, key = '') => {
    topicItemRefs[key] = el;
    const elNew: VNodeRef = el as unknown as VNodeRef;
    return elNew;
};

// 关闭富文本弹窗事件
const onCloseContentWindow = (html: string) => {
    // console.log('html: ', html);
    // console.log('global: ', global)
    if (global.focusItemKey && global.focusItemKey in global.focusItem) {
        global.focusItem[global.focusItemKey] = html;
        global.focusItem = {};
        global.focusItemKey = '';
    } else if (global.topicListNew[global.topicListIndex]?.answers[global.answerIndex] != undefined) {
        global.topicListNew[global.topicListIndex].answers[global.answerIndex].content = html;
        topicList.value = global.topicListNew;
        global.topicListIndex = 9999;
        global.answerIndex = 9999;
    }
    // console.log('topicList.value: ', JSON.parse(JSON.stringify(topicList.value)))
};

// 聚焦事件
const onFocus = async (item: AnyObj, key: keyof TopicItemType) => {
    global.focusItem = item;
    global.focusItemKey = key;
    try {
        // console.log('item[key]: ', item[key])
        // const html = await topicWindowRef.value?.show({
        //     html: item[key],
        // });
        // console.log('html: ', html);
        // item[key] = html;
        topicWindowRef.value?.show({
            html: item[key],
        });
        // console.log('topicList.value: ', JSON.parse(JSON.stringify(topicList.value)))
    } catch (error) {
        console.warn("error", error);
    }
};

// 答案选项聚焦事件
const onAnswerFocus = async (topicListIndex = 0, answerIndex = 0) => {
    // console.log('topicListIndex: ', topicListIndex);
    // console.log('answerIndex: ', answerIndex);
    global.topicListNew = JSON.parse(JSON.stringify(topicList.value));
    global.topicListIndex = topicListIndex;
    global.answerIndex = answerIndex;
    topicWindowRef.value?.show({
        html: topicList.value[topicListIndex]?.answers[answerIndex]?.content || '<p></p>',
        // html: '<p>asdsa<img src="https://loongteach.oss-cn-guangzhou.aliyuncs.com/shuxue/20240416/b87d6f4bff0b462a88bf4004f5f5c00d.png" alt="iconERP.png" data-href="https://loongteach.oss-cn-guangzhou.aliyuncs.com/shuxue/20240416/b87d6f4bff0b462a88bf4004f5f5c00d.png" style=""/></p>'
    });
    // console.log('topicListNew', topicList.value[topicListIndex].answers[answerIndex].content)
    // try {
    //     const html = await topicWindowRef.value?.show({
    //         html: topicList.value[topicListIndex].answers[answerIndex].content || '',
    //     }) as string;
    //     topicListNew[topicListIndex].answers[answerIndex].content = html;
    //     topicList.value = topicListNew;
    // } catch (error) {
    //     console.warn("error", error);
    // }
};

// 保存题目html文本内容事件
const onChangeHtml = () => {
    // console.log(global.focusItem);
    // console.log(topicList.value);
};

// 执行删除试题
const onDel = async (topic: TopicSave) => {
    const index = topicList.value.findIndex(item => item.uid === topic.uid);
    if (index > -1) topicList.value.splice(index, 1);
};

const choiceDtosItem = ['A', 'B', 'C', 'D', 'E', 'F', 'G'];

// 点击添加试题选项
const onAddOpt = (topic: TopicSaveApi) => {
    topic.choiceDtos.push({
        item: choiceDtosItem[topic.choiceDtos.length] || '',
        itemContent: ''
    });
};

// 点击添加试题答案
const onAddAnswer = (topic: TopicSaveApi) => {
    topic.answers.push({
        content: ''
    });
};

// 选择大纲事件
const onSetProgramId = (id = 0) => {
    global.programId = id;
};

// 点击添加题
const onAddTopic = (type: TopicTypeNumber) => {
    topicList.value.push({
        id: 0,
        content: '',
        type,
        answers: [{content: ''}],
        video: '',
        choiceDtos: type == 2 || type == 3 ? [
            {
                item: 'A',
                itemContent: ''
            }
        ] : [],
        categoryId: 0,
        categoryName: '',
        imgs: [],
        difficulty: 1,
        uid: createUuid(),
        sameFlg: '',
        score: 1
    });
};

// 点击保存全部
const submit = async () => {
    try {
        const keyArr = Object.keys(topicItemRefs);
        let validate = true;
        for (let i = 0; i < keyArr.length; i++) {
            if (topicItemRefs[keyArr[i]] && await topicItemRefs[keyArr[i]].validate() === false) {
                validate = false;
                break;
            }
        }
        if (!validate) return;
        const resArr = await Promise.allSettled(topicList.value.map(topicData => {
            let categoryId = topicData.categoryId;
            let categoryName = '';
            if (categoryList.value.findIndex(item => item.id == categoryId) < 0) {
                categoryName = String(categoryId);
                categoryId = 0;
            }
            return request({
                method: 'post',
                url: topicData.id > 0 ? '/questions/update' : '/questions/add',
                contentTypeIsForm: false,
                showLoading: {},
                errorToast: true,
                data: {
                    ...topicData,
                    categoryId,
                    categoryName
                }
            });
        }));
        // console.log('resArr: ', resArr);
        if (resArr.every(res => res.status === 'fulfilled')) {
            ElMessage({
                message: Number(route.params.id) == 0 ? `保存成功${resArr.length}题` : '编辑成功',
                type: 'success'
            });
            // if (route.params.id > '0') {
            //     routerBack();
            // }
            router.push({
                path: '/topicList'
            });
        }
    } catch (error) {
        console.warn(error);
    }
};

// 点击取消
const cancel = async () => {
    try {
        await ElMessageBox.confirm(
            '确认返回吗？',
            '提示',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }
        );
        routerBack();
    } catch (error) {
        
    }
};

// 获取分类列表
const getCategoryList = async () => {
    try {
        categoryList.value = await request({
            url: '/paper/category/list',
            method: 'post'
        });
    } catch (error) {
        
    }
}

// 获取详情
const getDetail = async () => {
    try {
        const detail = await request({
            url: '/questions/getOneById',
            method: 'post',
            contentTypeIsForm: true,
            showLoading: {},
            errorToast: true,
            data: {
                id: route.params.id
            }
        });
        topicList.value = [
            {
                ...detail,
                type: detail.questionsType || 1,
                answers: (detail.answers || []).map((answer: string) => {
                    return {
                        content: answer
                    }
                }),
                choiceDtos: (detail.choiceDtos || []).map((item: any, index: number) => {
                    return {
                        item: choiceDtosItem[index],
                        itemContent: item.itemContent
                    }
                }),
                sameFlg: detail.sameFlg || '',
            }
        ];
    } catch (error) {
        
    }
};

const onShow = async () => {
    // initSortable();
    Object.keys(topicItemRefs).forEach(key => {
        if (key in topicItemRefs) delete topicItemRefs[key];
    });
    global.detail = {};
    getCategoryList();
    if (Number(route.params.id) > 0) {
        getDetail();
    }
};

onMounted(onShow);
</script>

<style lang="scss" scoped>
@import './UpdateTopic.scss';
</style>

<style lang="scss">
.toppic-update-list-sortable-drag {
    width: 100%;
    background: #6b92ff;
    color: #ffffff;
    height: 86px;
    display: flex;
    align-items: center;
    justify-content: center;
}
</style>